package cn.jjxx.modules.sys.controller;

import cn.jjxx.core.common.data.DuplicateValid;
import cn.jjxx.core.common.entity.ZtreeEntity;
import cn.jjxx.core.model.AjaxJson;
import cn.jjxx.core.model.PageJson;
import cn.jjxx.core.model.ValidJson;
import cn.jjxx.core.query.annotation.PageableDefaults;
import cn.jjxx.core.query.data.PropertyPreFilterable;
import cn.jjxx.core.query.data.Queryable;
import cn.jjxx.core.query.utils.QueryableConvertUtils;
import cn.jjxx.core.query.wrapper.EntityWrapper;
import cn.jjxx.core.security.shiro.authz.annotation.RequiresMethodPermissions;
import cn.jjxx.core.utils.MessageUtils;
import cn.jjxx.core.utils.ObjectUtils;
import cn.jjxx.core.utils.StringUtils;
import cn.jjxx.core.utils.TreeBuilder;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializeFilter;
import com.baomidou.mybatisplus.annotations.TableName;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import cn.jjxx.core.common.controller.BaseBeanController;
import cn.jjxx.core.security.shiro.authz.annotation.RequiresPathPermission;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import cn.jjxx.modules.sys.entity.Menu;
import cn.jjxx.modules.sys.entity.User;
import cn.jjxx.modules.sys.utils.UserUtils;
import cn.jjxx.core.config.BillConfig;
import cn.jjxx.modules.sys.entity.BillActConfig;
import cn.jjxx.modules.sys.service.IBillActConfigService;
import cn.jjxx.modules.sys.service.IMenuService;
import cn.jjxx.modules.map.service.ICommonMapService;
/**   
 * @Title: 系统流程单据信息配置
 * @Description: 系统流程单据信息配置
 * @author zcg
 * @date 2018-08-27 17:29:43
 * @version V1.0   
 *
 */
@Controller
@RequestMapping("${admin.url.prefix}/sys/billactconfig")
@RequiresPathPermission("sys:billactconfig")
public class BillActConfigController extends BaseBeanController<BillActConfig> {

    @Autowired
    protected IBillActConfigService billActConfigService;
    @Autowired
    protected ICommonMapService commonMapService;
    @Autowired
    protected IMenuService menuService;

	/**
	 * @Description: 根据获取系统流程单据信息配置的实体数据 .<br>
	 * @param id 主键Id.<br>
	 * @author zcg .<br>
	 * @date 2018-08-27 17:29:43.<br>
	 */
    public BillActConfig get(String id) {
        if (!ObjectUtils.isNullOrEmpty(id)) {
            return billActConfigService.selectById(id);
        } else {
            return newModel();
        }
    }

	/**
	 * @Description: 跳转至系统流程单据信息配置的列表界面 .<br>
	 * @author zcg .<br>
	 * @date 2018-08-27 17:29:43.<br>
	 */
    @RequiresMethodPermissions("list")
    @RequestMapping(method = RequestMethod.GET)
    public String list(Model model, HttpServletRequest request, HttpServletResponse response) {
    	//获取菜单
    	List<ZtreeEntity> trees = menuService.getMenuTree();
    	List<ZtreeEntity> list = TreeBuilder.bulid(trees);
    	String content = JSON.toJSONString(list);
    	request.setAttribute("trees", content);
        return display("list");
    }

	/**
	 * @Description: 系统流程单据信息配置的列表界面获取列表结果 .<br>
	 * @author zcg .<br>
	 * @date 2018-08-27 17:29:43.<br>
	 */
    @RequestMapping(value = "ajaxList", method = { RequestMethod.GET, RequestMethod.POST })
    @PageableDefaults(sort = "id=desc")
    private void ajaxList(Queryable queryable, PropertyPreFilterable propertyPreFilterable, HttpServletRequest request,
                          HttpServletResponse response) throws IOException {
        EntityWrapper<BillActConfig> entityWrapper = new EntityWrapper<BillActConfig>(entityClass);
        String menuId = request.getParameter("nodeId");
        if(StringUtils.isNotEmpty(menuId)){
        	entityWrapper.eq("menuId", menuId);
        }
        entityWrapper.setTableAlias("t.");
        entityWrapper.eq("1", 1);
        propertyPreFilterable.addQueryProperty("id");
        // 预处理
        QueryableConvertUtils.convertQueryValueToEntityValue(queryable, entityClass);
        SerializeFilter filter = propertyPreFilterable.constructFilter(entityClass);
        PageJson<BillActConfig> pagejson = new PageJson<BillActConfig>(billActConfigService.list(queryable,entityWrapper));
        String content = JSON.toJSONString(pagejson, filter);
        StringUtils.printJson(response, content);
    }

	/**
	 * @Description: 跳转至系统流程单据信息配置的添加界面 .<br>
	 * @author zcg .<br>
	 * @date 2018-08-27 17:29:43.<br>
	 */
    @RequestMapping(value = "create", method = RequestMethod.GET)
    public String create(Model model, HttpServletRequest request, HttpServletResponse response) {
        BillActConfig billActConfig = new BillActConfig();
        String menuId = request.getParameter("menuId");
        Menu menu = menuService.selectById(menuId);
        billActConfig.setMenuId(menu.getId());
        billActConfig.setMenuName(menu.getName());
        request.setAttribute("data", billActConfig);
        return display("edit");
    }
    
	/**
	 * @Description: 新增系统流程单据信息配置的数据 .<br>
	 * @param billActConfig 系统流程单据信息配置实体类.<br>
	 * @author zcg .<br>
	 * @date 2018-08-27 17:29:43.<br>
	 */
    @RequestMapping(value = "create", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson create(Model model, @Valid @ModelAttribute("data") BillActConfig billActConfig, BindingResult result,
                           HttpServletRequest request, HttpServletResponse response) {
    	return doSave(billActConfig, request, response, result);
    }
	/**
	 * @Description: 跳转至系统流程单据信息配置的更新界面 .<br>
	 * @author zcg .<br>
	 * @date 2018-08-27 17:29:43.<br>
	 */
    @RequestMapping(value = "{id}/update", method = RequestMethod.GET)
    public String update(@PathVariable("id") String id, Model model, HttpServletRequest request,
                              HttpServletResponse response) {
        BillActConfig billActConfig = get(id);
        model.addAttribute("data", billActConfig);
        return display("edit");
    }

	/**
	 * @Description: 修改系统流程单据信息配置的数据 .<br>
	 * @param billActConfig 系统流程单据信息配置实体类.<br>
	 * @author zcg .<br>
	 * @date 2018-08-27 17:29:43.<br>
	 */
    @RequestMapping(value = "{id}/update", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson update(Model model, @Valid @ModelAttribute("data") BillActConfig billActConfig, BindingResult result,
                           HttpServletRequest request, HttpServletResponse response) {
        return doSave(billActConfig, request, response, result);
    }
	/**
	 * @Description: 执行保存系统流程单据信息配置的数据操作 .<br>
	 * @param billActConfig 系统流程单据信息配置实体类.<br>
	 * @author zcg .<br>
	 * @date 2018-08-27 17:29:43.<br>
	 */
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson doSave(BillActConfig billActConfig, HttpServletRequest request, HttpServletResponse response,
                           BindingResult result) {
        AjaxJson ajaxJson = new AjaxJson();
        ajaxJson.success("保存成功");
        if (hasError(billActConfig, result)) {
            // 错误提示
            String errorMsg = errorMsg(result);
            if (!StringUtils.isEmpty(errorMsg)) {
                ajaxJson.fail(errorMsg);
            } else {
                ajaxJson.fail("保存失败");
            }
            return ajaxJson;
        }
        try {
        	billActConfig.setNoticeTemplet(billActConfig.getNoticeTemplet().trim());
            if (StringUtils.isEmpty(billActConfig.getId())) {
                billActConfigService.insert(billActConfig);
            } else {
                billActConfigService.insertOrUpdate(billActConfig);
            }
        } catch (Exception e) {
            e.printStackTrace();
            ajaxJson.fail("保存失败!<br />原因:" + e.getMessage());
        }
        return ajaxJson;
    }

	/**
	 * @Description: 单条删除系统流程单据信息配置 .<br>
	 * @param id 单据Id.<br>
	 * @author zcg .<br>
	 * @date 2018-08-27 17:29:43.<br>
	 */
    @RequestMapping(value = "{id}/delete", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson delete(@PathVariable("id") String id) {
        AjaxJson ajaxJson = new AjaxJson();
        ajaxJson.success("删除成功");
        TableName table = BillActConfig.class.getAnnotation(TableName.class);
    	String tableName = table.value();
		String dbName = MessageUtils.getMessage("connection.dbname");
        try {
        	List<String> ids = Arrays.asList(id.split(","));
        	//得到被其他表引用的结果
			String quoteMsg = commonMapService.quoteMsg(dbName, tableName, ids);
			if(StringUtils.isNotEmpty(quoteMsg)){
				ajaxJson.setMsg("删除失败,"+quoteMsg);
				return ajaxJson;
			}
            billActConfigService.deleteById(id);
        } catch (Exception e) {
            e.printStackTrace();
            ajaxJson.fail("删除失败");
        }
        return ajaxJson;
    }

	/**
	 * @Description: 执行保存系统流程单据信息配置的数据操作 .<br>
	 * @param ids 单据Id集合.<br>
	 * @author zcg .<br>
	 * @date 2018-08-27 17:29:43.<br>
	 */
    @RequestMapping(value = "batch/delete", method = { RequestMethod.GET, RequestMethod.POST })
    @ResponseBody
    public AjaxJson batchDelete(@RequestParam(value = "ids", required = false) String[] ids) {
        AjaxJson ajaxJson = new AjaxJson();
        ajaxJson.success("批量删除成功");
        TableName table = BillActConfig.class.getAnnotation(TableName.class);
    	String tableName = table.value();
		String dbName = MessageUtils.getMessage("connection.dbname");
        try {
            List<String> idList = java.util.Arrays.asList(ids);
            //得到被其他表引用的结果
			String quoteMsg = commonMapService.quoteMsg(dbName, tableName, idList);
			if(StringUtils.isNotEmpty(quoteMsg)){
				ajaxJson.setMsg("批量删除失败,"+quoteMsg);
				return ajaxJson;
			}
            billActConfigService.deleteBatchIds(idList);
        } catch (Exception e) {
            e.printStackTrace();
            ajaxJson.fail("批量删除失败");
        }
        return ajaxJson;
    }

	/**
	 * @Description: 跳转至系统流程单据信息配置的查看界面 .<br>
	 * @param ids 单据Id.<br>
	 * @author zcg .<br>
	 * @date 2018-08-27 17:29:43.<br>
	 */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public String view(Model model, @PathVariable("id") String id, HttpServletRequest request,
                       HttpServletResponse response) {
        BillActConfig billActConfig = get(id);
        model.addAttribute("data", billActConfig);
        return display("edit");
    }

	/**
	 * @Description: 验证系统流程单据信息配置功能数据的唯一性 .<br>
	 * @param duplicateValid 校验实体类.<br>
	 * @author zcg .<br>
	 * @date 2018-08-27 17:29:43.<br>
	 */
    @RequestMapping(value = "validate", method = { RequestMethod.GET, RequestMethod.POST })
    @ResponseBody
    public ValidJson validate(DuplicateValid duplicateValid, HttpServletRequest request) {
        ValidJson validJson = new ValidJson();
        Boolean valid = Boolean.FALSE;
        try {
            EntityWrapper<BillActConfig> entityWrapper = new EntityWrapper<BillActConfig>(entityClass);
            valid = billActConfigService.doValid(duplicateValid,entityWrapper);
            if (valid) {
                validJson.setStatus("y");
                validJson.setInfo("验证通过!");
            } else {
                validJson.setStatus("n");
                if (!StringUtils.isEmpty(duplicateValid.getErrorMsg())) {
                    validJson.setInfo(duplicateValid.getErrorMsg());
                } else {
                    validJson.setInfo("当前信息重复!");
                }
            }
        } catch (Exception e) {
            validJson.setStatus("n");
            validJson.setInfo("验证异常，请检查字段是否正确!");
        }
        return validJson;
    }
    
    
    
    
    
    
    
    
    
    /**
     * @Description: 得到可以被审核的单据 .<br>
     * @param bills 单据Id集合.<br>
     * @param status 可操作状态.<br>
     * @author zcg .<br>
     * @date 2018-08-27 17:29:43 .<br>
     */
    private List<String> getAllowOptBills(List<String> bills,String status){
    	EntityWrapper<BillActConfig> wrapper = new EntityWrapper<BillActConfig>();
    	wrapper.in("id", bills);
    	wrapper.eq("status", status);
    	List<BillActConfig> list = billActConfigService.selectList(wrapper);
    	bills = new ArrayList<String>();
    	for(BillActConfig bean:list){
    		bills.add(bean.getId());
    	}
    	return bills;
    }
    
    /**
     * @Description: 设置批量更新参数 .<br>
     * @param bills 可以操作的Id集合.<br>
     * @param newStatus 被修改的状态设置值.<br>
     * @author zcg .<br>
     * @date 2018-08-27 17:29:43 .<br>
     */
    private List<BillActConfig> setBacthUpdate(List<String> bills,String newStatus){
    	List<BillActConfig> list = new ArrayList<BillActConfig>();
    	User user = UserUtils.getUser();
    	if(bills.size()>0){
    		list = billActConfigService.selectBatchIds(bills);
        	for(BillActConfig bean:list){
        		bean.setStatus(Integer.valueOf(newStatus));
        		if(newStatus.equals(String.valueOf(BillConfig.SAVE))||
        				newStatus.equals(String.valueOf(BillConfig.SUBMIT))){
        		}
        	}
    	}
    	return list;
    }
}
